#!/usr/bin/env node

const Koa = require('koa'),
      KS  = require('koa-static'),
      fs  = require('fs'),
      Router = require('koa-router'),
      chapterList = require('./data.js');

const app = new Koa();
const router = new Router();

app.use(KS('./'));
var arr = [];
arr = chapterList.chapterList;

var brr = [];
for(let i = 0; i < arr.length; i++){
  brr[i] = arr[i].publishTimer;
}

for(let i = 0; i < brr.length; i++){
  for(let j = i; j > 0; j--){
    let a = brr[j].split('-');
    let b = brr[j-1].split('-');
    if(a[0] > b[0]){
      [arr[j],arr[j-1]] = [arr[j-1],arr[j]];
      [brr[j],brr[j-1]] = [brr[j-1],brr[j]];
    }else if(a[0] == b[0]){
      if(a[1] > b[1]){
        [arr[j],arr[j-1]] = [arr[j-1],arr[j]];
        [brr[j],brr[j-1]] = [brr[j-1],brr[j]];
      }else if(a[1] == b[1]){
        if(a[2] > b[2]){
          [arr[j],arr[j-1]] = [arr[j-1],arr[j]];
          [brr[j],brr[j-1]] = [brr[j-1],brr[j]];
        }
      }
    }
  }
}

app.use(async (ctx,next) => {
  ctx.response.type = 'html';
  ctx.response.body = fs.createReadStream('chapters.html');
  next();
});

router.get('/getlist',async (ctx,next) => {
  ctx.body = JSON.stringify(arr);
  next();
})

app.use(router.routes());

app.listen(8080);

//http.createServer((req,res) => {
//  
//  let ads = url.parse(req.url);
//  //ads.path = '.'+ads.path;
//  //ads.href = '.' + ads.href;
//  //console.log(ads.href);
//  if(ads.pathname === '/'){
//    fs.readFile('./chapters.html',function(err,data){
//      if(!err){
//        res.end(data);
//      }else{
//        console.log(err);
//      }
//    });
//  }else if(ads.pathname === '/getlist'){
//    res.writeHead(200,{
//      'Content-type':'application/json'
//    }); 
//    
//    let a = JSON.stringify(arr);
//    res.end(a);
//  }else if(ads.pathname === '/favicon.ico'){
//    res.setHeader('content-type','text/html');
//  }else{
//    fs.readFile('.'+req.url,function(err,data){
//      if(!err){
//        res.end(data);
//      }else{
//        console.log(err);
//      }
//    });
//  }
//
//  console.log(ads);
//  //ads.pathname = '.'+ads.pathname;
//
//  //ads.href = '.'+ads.href;
//  //console.log(ads.pathname);
//  //console.log(ads.path);
//  //console.log(ads);
//
//  
//  res.writeHead(200,{
//    'Content-type':'text/html; charset=utf-8'
//  });
//  res.end(html);
//}).listen(8080);
